<template>
  <div class="app-container customer-div">
    <el-menu :default-active="contactParams.type" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="self">我负责的</el-menu-item>
<!--      <el-menu-item index="sub" v-if="isCanCustomerByDept">部门</el-menu-item>-->
<!--      <el-menu-item index="all" v-if="isCanCustomerByAll">全部</el-menu-item>-->
    </el-menu>
    <div style="margin-top: 20px">
      <el-button
              size="small"
              v-if="contactParams.type=='self'"
              @click="showContact('add',null)"
              type="primary">
        新增联系人
      </el-button>
    </div>
    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="contactParams" size="mini" label-width="120px">
        <el-form-item label="客户名称：">
          <el-select
            clearable
            v-model="contactParams.customerId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="loading">
            <el-option
              v-for="item in customerList"
              :key="item.customerId"
              :label="item.customerName"
              :value="item.customerId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人姓名：">
          <el-input v-model="contactParams.contactName" placeholder="请输入" style="width:195px"></el-input>
        </el-form-item>
        <el-form-item label="联系人手机：">
          <el-input v-model="contactParams.contactMobile" placeholder="请输入" style="width:195px"></el-input>
        </el-form-item>
        <el-form-item label="最后联系日期：">
          <el-date-picker
            :default-time="['00:00:00', '23:59:59']"
            v-model="contactParams.trackingTime"
            value-format="timestamp"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建日期：">
          <el-date-picker
            :default-time="['00:00:00', '23:59:59']"
            v-model="contactParams.createTime"
            value-format="timestamp"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新日期：">
          <el-date-picker
            :default-time="['00:00:00', '23:59:59']"
            v-model="contactParams.updateTime"
            value-format="timestamp"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="产品线：">
          <el-select v-model.number="contactParams.goodsLineId" class="input-width" style="width:195px" placeholder="请选择" clearable >
            <el-option :label="item.cddValue" v-for="item in goodsLineList" :value="item.cddId" :key="item.cddId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--数据列表-->
    <div class="table-container">
      <el-table
        v-loading="contactLoading"
        :data="contactPageList"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column
                label="公司名称"
                width="300">
          <template slot-scope="scope">
            <el-link @click="toDetail(scope.row)" type="primary">
              {{scope.row.customerName}}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column
          prop="contactName"
          label="联系人姓名"
          width="100">
        </el-table-column>
        <el-table-column
          prop="contactMobile"
          label="联系方式"
          align="center"
          width="180">
        </el-table-column>
        <el-table-column
          label="是否为主联系人"
          align="center"
          width="150">
          <template slot-scope="scope">
            {{scope.row.isMainContact == 1 ? '是' : '否'}}
          </template>
        </el-table-column>
        <el-table-column
                label="是否有采购决定权"
                align="center"
                width="150">
          <template slot-scope="scope">
            {{scope.row.isBuyPermission == 1 ? '是' : '否'}}
          </template>
        </el-table-column>
        <el-table-column
          prop="lastTrackingTime"
          label="最近联系日期"
          width="150"
          align="center">
          <template slot-scope="scope">
            {{scope.row.lastTrackingTime | formatTime}}
          </template>
        </el-table-column>
        <el-table-column
                align="center"
                prop="goodsLineNames"
                label="产品线"
                width="150">
        </el-table-column>
        <el-table-column
          prop="contactFocus"
          label="关注点"
          width="150">
        </el-table-column>
        <el-table-column
          label="爱好"
          width="150">
          <template slot-scope="scope">
            {{scope.row.contactHobby}}
          </template>
        </el-table-column>
        <el-table-column
          label="创建日期"
          width="150"
          align="center">
          <template slot-scope="scope">
            {{scope.row.createdAt}}
          </template>
        </el-table-column>
        <el-table-column
          label="创建人"
          width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.createUserName}}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          align="center">
          <template slot-scope="scope">
            <el-button
              v-if="contactParams.type=='self'"
              type="text"
              size="mini"
              @click="showContact('edit',scope.row)">编辑
            </el-button>
            <el-button
                    v-if="contactParams.type!='self'"
                    type="text"
                    size="mini"
                    @click="showContact('see',scope.row)">查看
            </el-button>
            <el-button
              v-if="contactParams.type=='self'"
              @click="delConTact(scope.row)"
              type="text"
              size="mini"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChangeContact"
        @current-change="handleCurrentChangeContact"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="contactParams.pageNum"
        :page-size="contactParams.pageSize"
        :page-sizes="[10,15,20]"
        :total="contactCount">
      </el-pagination>
    </div>

    <!--新增/编辑联系人-->
    <el-dialog
            :close-on-click-modal="false"
      :title="title3"
      :beforeClose="handleClose3"
      :visible.sync="dialogVisible3"
      width="600px">
      <el-form :model="contactForm" size="mini" label-width="120px" :rules="rules3" ref="contactForm">
        <el-form-item label="客户名称：" prop="customerId">
          <el-select
            :disabled="showContactType!='add'"
            v-model="contactForm.customerId"
            filterable
            remote
            reserve-keyword
            :remote-method="remoteMethod2"
            :loading="loading">
            <el-option
              v-for="item in customerList2"
              :key="item.customerId"
              :label="item.customerName"
              :value="item.customerId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=" 联系人姓名：" prop="contactName">
          <el-input v-model="contactForm.contactName" style="width:150px" :disabled="showContactType == 'see'"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="contactMobile">
          <el-input v-model="contactForm.contactMobile" style="width:150px" :disabled="showContactType == 'see'" @blur="seachRepeat"></el-input>
        </el-form-item>
        <el-form-item label="职务：" prop="contactDuty">
          <el-input v-model="contactForm.contactDuty" style="width:150px" :disabled="showContactType == 'see'"></el-input>
        </el-form-item>
        <el-form-item label="关注点：">
          <el-input v-model="contactForm.contactFocus" type="textarea" :rows="2" :disabled="showContactType == 'see'" :autosize="{ minRows: 2, maxRows: 6}"></el-input>
        </el-form-item>
        <el-form-item label="爱好：">
          <el-input v-model="contactForm.contactHobby" type="textarea" :rows="2" :disabled="showContactType == 'see'" :autosize="{ minRows: 2, maxRows: 6}"></el-input>
        </el-form-item>
        <el-form-item label="设为主联系人：">
          <el-radio-group v-model="contactForm.isMainContact" :disabled="showContactType == 'see'">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否有采购决定权：">
          <el-radio-group v-model="contactForm.isBuyPermission" :disabled="showContactType == 'see'">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <div style="margin:20px 0;font-weight: bold;cursor: pointer" @click="isShowMore = !isShowMore">更多信息 <i :class="{'el-icon-caret-bottom':!isShowMore,'el-icon-caret-top':isShowMore}"></i></div>
        <div v-if="isShowMore">
          <el-form-item label="邮件：">
            <el-input v-model="contactForm.contactEmail" style="width:150px" :disabled="showContactType == 'see'"></el-input>
          </el-form-item>
          <el-form-item label="地址：">
            <el-input v-model="contactForm.contactAddress" type="textarea" :rows="2" :disabled="showContactType == 'see'" :autosize="{ minRows: 2, maxRows: 6}"></el-input>
          </el-form-item>
          <el-form-item label="性别：">
            <el-radio-group v-model="contactForm.contactSex" :disabled="showContactType == 'see'">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="出生日期：" prop="trackingTime">
            <el-date-picker
              :disabled="showContactType == 'see'"
              v-model="contactForm.contactBirthday"
              align="right"
              type="date"
              value-format="yyyy-MM-dd"
              format="yyyy 年 MM 月 dd 日"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="备注：">
            <el-input v-model="contactForm.remark" type="textarea" :rows="2" :disabled="showContactType == 'see'" :autosize="{ minRows: 2, maxRows: 6}"></el-input>
          </el-form-item>
        </div>

      </el-form>
      <span slot="footer" class="dialog-footer" v-if="showContactType != 'see'">
          <el-button @click="handleClose3">取 消</el-button>
          <el-button type="primary" @click="handleConfirm3" :loading="btnLoading3">确 定</el-button>
      </span>
      <span slot="footer" class="dialog-footer" v-else>
          <el-button @click="handleClose3">关 闭</el-button>
      </span>
    </el-dialog>

    <!--联系人删除-->
    <el-dialog
            :close-on-click-modal="false"
            title="联系人删除"
            :visible.sync="dialogVisible4"
            width="420px">
      <div style="font-size:14px;padding-bottom:20px;">确认删除联系人？</div>
      <el-form :model="delForm" size="mini" label-width="120px" ref="delForm" :rules="rules4">
        <el-form-item label="删除理由：" prop="remark">
          <el-input v-model="delForm.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 6}"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose4">取 消</el-button>
          <el-button type="primary" @click="handleConfirm4" :loading="btnLoading4">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
    import {getContactPageList,
        editContactInfo,
        addContact,
        getCustomerOption,delContactInf,checkContactMobile,delContactInfo,getCustomerSetting} from '@/api/partner'
    import {formatDate} from '@/utils/date';
    import {validatePhone} from '@/utils/validate';
    import store from '@/store';
    import { mapGetters } from 'vuex'
    const defaultContactForm = {
        customerId:'',
        customerName:'',
        contactName:'',
        contactMobile:'',
        contactDuty:'',
        contactHobby:'',
        contactFocus:'',
        contactAddress:'',
        contactSex:'',
        contactEmail:'',
        contactBirthday:'',
        isMainContact:'',
        remark:'',
        isBuyPermission:'',
    };
    export default {
        name: "index",
        data(){
            const isvalidatePhone = (rule, value, callback) => {
                if(!validatePhone(value)){
                    callback(new Error('请输入正确的手机号'))
                } else {
                    callback()
                }
            };
            return{
                roles:store.getters.roles ? store.getters.roles : [],
                contactPageList :[],
                contactCount :0,
                contactLoading :false,
                dialogVisible3:false,
                isShowMore:true,
                title3:'',
                btnLoading3:false,
                contactParams:{
                    pageNum:1,
                    pageSize:10,
                    customerId:'',
                    contactName:'',
                    contactMobile:'',
                    createTime:null,
                    updateTime:null,
                    trackingTime:null,
                    goodsLineId:'',
                    type:'self',
                },
                contactForm:JSON.parse(JSON.stringify(defaultContactForm)),
                rules3:{
                    customerId:[{required: true, message: '请选择客户', trigger: 'change'},],
                    contactName:[{required: true, message: '请填写联系人姓名', trigger: 'blur'},],
                    contactMobile:[{required: true,  trigger: 'blur', validator: isvalidatePhone},],
                    contactDuty:[{required: true, message: '请填写联系人职务', trigger: 'blur'},],
                },
                loading:false,
                customerList:[],
                customerList2:[],
                showContactType:'',
                dialogVisible4:false,
                btnLoading4:false,
                curItem:{},
                rules4:{
                  remark:[{required: true, message: '请输入删除理由', trigger: 'blur'},],
                },
              delForm:{
                remark:''
              },
              goodsLineList:[]
            }
        },
        created() {
           this.getCustomerSettingList();
           this.getPageContactListData();

        },
        computed: {
          ...mapGetters([
            'name',
            'mobile',
            'userId'
          ]),
            isCanContactsByAdd() {
                if(this.roles.indexOf("contactsByAdd") != -1){
                    return true
                }else{
                    return false
                }
            },
            isCanContactsByEdit(){
                if(this.roles.indexOf("contactsByEdit") != -1){
                    return true
                }else{
                    return false
                }
            },
            isCanContactsDelete(){
                if(this.roles.indexOf("contactsDelete") != -1){
                    return true
                }else{
                    return false
                }
            },
            isCanCustomerByDept(){
              if(this.roles.indexOf("customerByDept") != -1){
                return true
              }else{
                return false
              }
            },
            isCanCustomerByAll(){
              if(this.roles.indexOf("customerByAll") != -1){
                return true
              }else{
                return false
              }
            },
        },
        filters: {
            formatTime(time) {
                if(time){
                    let date = new Date(time);
                    return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
                }else{
                    return ''
                }

            },
        },
        methods:{
          //获取客户配置
          getCustomerSettingList(){
            getCustomerSetting().then((res)=>{
              res.forEach((el)=>{
               if(el.cdtCode == 'goods_line'){
                  this.goodsLineList = el.data
                }
              });
            })
          },

          //查询手机号是否存在
          seachRepeat(){
            if(validatePhone(this.contactForm.contactMobile) && this.contactForm.customerId != ''){
              checkContactMobile({contactMobile:this.contactForm.contactMobile,customerId:this.contactForm.customerId}).then((res)=>{
              }).catch((rej)=>{
                if (rej.code == 10000 || rej.code == 10001) {
                  this.$message.error(rej.msg);
                  this.contactForm.contactMobile = '';
                }
              })
            }

          },
          //去详情页
          toDetail(item){
            this.$router.push({name:'customerDetail',query:{id:item.customerId}})
          },
            //获取客户列表
            remoteMethod(query) {
                if(query && query!= ''){
                    this.loading = true;
                    getCustomerOption({keywords:query}).then(response => {
                        this.customerList = response;
                        this.loading = false;
                    }).catch(()=>{
                        this.loading = false;
                    });
                }
            },
            //获取客户列表
            remoteMethod2(query) {
                if(query && query!= ''){
                    this.loading = true;
                  let data = {};
                  data.keywords = query;
                  if(this.contactParams.type == 'self'){
                    data.chargeId = this.userId
                  }
                    getCustomerOption(data).then(response => {
                        this.customerList2 = response;
                        this.loading = false;
                    }).catch(()=>{
                        this.loading = false;
                    });
                }

            },
            /**
             * 切换选择状态
             */
            handleSelect(key, keyPath){
                this.contactParams.type = key;
                this.handleSearchList();
            },
            handleSearchList(){
                this.contactParams.pageNum = 1;
                this.getPageContactListData();
            },
            //获取页面联系人列表
            getPageContactListData(){
                this.contactLoading = true;
                let data = JSON.parse(JSON.stringify(this.contactParams));
                if(data.createTime){
                    data.createTime[0] = data.createTime[0]/1000;
                    data.createTime[1] = data.createTime[1]/1000;
                }
                if(data.updateTime){
                    data.updateTime[0] = data.updateTime[0]/1000;
                    data.updateTime[1] = data.updateTime[1]/1000;
                }
                if(data.trackingTime){
                    data.trackingTime[0] = data.trackingTime[0]/1000;
                    data.trackingTime[1] = data.trackingTime[1]/1000;
                }
                getContactPageList(data).then((res)=>{
                    this.contactPageList = res.list;
                    this.contactCount = res.count;
                    this.contactLoading = false;
                }).catch(()=>{
                    this.contactLoading = false;
                })
            },

            handleSizeChangeContact(val){
                this.contactParams.pageNum = 1;
                this.contactParams.pageSize = val;
                this.getPageContactListData();
            },
            handleCurrentChangeContact(val){
                this.contactParams.pageNum = val;
                this.getPageContactListData();
            },

            //切换是否为主联系人
            changeMainContact(item){
                let data = {};
                data.contactId = item.contactId;
                data.isMainContact = item.isMainContact;
                editContactInfo(data).then((res)=>{
                    this.getPageContactListData();
                })
            },

            //显示联系人弹窗
            showContact(type,item){
                this.isShowMore = true;
                this.dialogVisible3 = true;
                this.showContactType = type;
                if(type == 'add'){
                    this.title3 = '新增联系人';
                    this.contactForm = JSON.parse(JSON.stringify(defaultContactForm));
                }else{
                    this.title3 = type=='edit' ? '编辑联系人' : '查看联系人';
                    this.contactForm = JSON.parse(JSON.stringify(item));
                    this.remoteMethod2(item.customerName);
                }
            },

            //关闭联系人弹窗
            handleClose3(){
                this.$refs.contactForm.clearValidate();
                this.dialogVisible3 = false;
                this.btnLoading3 = false;
                this.customerList2 = [];
            },

            //提交联系人
            handleConfirm3(){
                this.$refs.contactForm.validate((valid) => {
                    if (valid) {
                        this.btnLoading3 = true;
                        let data = JSON.parse(JSON.stringify(this.contactForm));
                        let fn = data.contactId ? editContactInfo : addContact;
                        fn(data).then((res)=>{
                            this.btnLoading3 = false;
                            this.handleClose3();
                            this.getPageContactListData();
                        })
                    }
                })
            },

          //显示删除联系人
          delConTact(item){
              this.curItem = JSON.parse(JSON.stringify(item));
              this.dialogVisible4 = true;
          },


          //关闭删除弹窗
          handleClose4(){
            this.dialogVisible4 = false;
            this.btnLoading4 = false;
            this.delForm.remark = '';
          },

          //确认删除
          handleConfirm4(){
            this.$refs.delForm.validate((valid) => {
              if (valid) {
                this.btnLoading4 = true;
                let data = {};
                data.contactId = this.curItem.contactId;
                data.remark = this.delForm.remark;
                delContactInfo(data).then((res)=>{
                  this.$message({
                    type: 'success',
                    message: '删除成功!'
                  });
                  this.btnLoading4 = false;
                  this.handleClose4();
                  this.getPageContactListData();
                }).catch(()=>{
                  this.btnLoading4 = false;
                })
              }
            })

          },


        },
    }
</script>

<style scoped lang="scss">
  .customer-div{

  }
</style>
